package com.sl.pmpclient.businesses;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;

import android.content.ContentValues;
import android.content.Context;

import com.sl.pmpclient.utils.DataRecordUtil;
import com.sl.pmpclient.utils.GlobalVariablesUtil;
import com.sl.pmpclient.utils.HttpUtil;
import com.sl.pmpclient.utils.MD5Util;

/**
 * 处理身份验证的类
 * 
 * @author 烁灵
 * 
 */

public class AuthBusiness {
	/**
	 * 将登录的用户记在全局中
	 * 
	 * @param context
	 * @param userid
	 * @param username
	 * @return
	 */
	public static boolean appSetUser(Context context, int userid,
			String username) {
		((GlobalVariablesUtil) context.getApplicationContext())
				.setUserid(userid);
		((GlobalVariablesUtil) context.getApplicationContext())
				.setUsername(username);
		return true;
	}

	/**
	 * 删除被记住的密码
	 * 
	 * @param context
	 * @param username
	 * @return
	 */
	public static boolean deleteRememberedUser(Context context, String username) {
		return DataRecordUtil.deleteRememberedUser(context, username);
	}

	/**
	 * 取最近一个被记住的用户
	 * 
	 * @param context
	 * @return 若没有则返回null
	 */
	public static ContentValues getFirstRememberedUserInfo(Context context) {
		ArrayList<ContentValues> list = DataRecordUtil
				.getAllRememberedUsers(context);
		if (list.size() == 0) {
			return null;
		}
		return list.get(0);
	}

	/**
	 * 判断用户是否被记住并返回记住的密码
	 * 
	 * @param context
	 * @param username
	 * @return
	 */
	public static String isUserRemembered(Context context, String username) {
		ContentValues uservalue = DataRecordUtil.getRememberedUserPswByName(
				context, username);
		if (uservalue != null) {
			return uservalue.getAsString("remembered_user_psw");
		}
		return null;
	}

	/**
	 * 登录验证
	 * 
	 * @param username
	 * @param password
	 * @param remembered
	 *            为true，则password为加密后的密码
	 * @return
	 */
	public static int loginUser(Context context, String username,
			String password, boolean remembered) {
		if (!remembered) {
			password = MD5Util.getMD5Str(password);
		}
		// 提交post请求验证用户
		Map<String, String> map = new HashMap<String, String>();
		map.put("user_name", username);
		map.put("user_psw", password);
		int userid = -1;
		try {
			userid = Integer.parseInt(HttpUtil.postRequest("login.php", map));
			if (userid != -1) {
				return userid;
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return userid;
	}

	/**
	 * 记住用户密码
	 * 
	 * @return
	 */
	public static boolean rememberUser(Context context, String username,
			String password) {
		password = MD5Util.getMD5Str(password);
		return DataRecordUtil.insertRememberedUser(context, username, password);
	}

}
